import axios from "axios"
import {Message} from 'element-ui';

const Requests = (all_query) => {
  console.log(all_query)
  // 处理请求入参-参数值为空则删除该参数键值
  /*for (let item in all_query.querys) {
    if (all_query.querys[item] === null || all_query.querys[item] === "undefined" || String(all_query.querys[item]).length === 0) {
      delete all_query.querys[item]
    }
  }*/

  const path = all_query.apiPath
  const method = all_query.method
  const querys = all_query.querys
  return new Promise((resolve, reject) => {
    /* 单独处理判断有无token */
    let headers = {
      "content-type": "application/json",
    }
    try {
      if (sessionStorage.getItem("token").length > 0) {
        headers["token"] = sessionStorage.getItem("token")
      }
    } catch (e) {
      console.log(e)
    }

    // console.log(headers)
    // Send a POST request
    let reqObj = { }
    if(method === 'get'){
      reqObj['params'] = querys
    }
    if(method === 'post'){
      reqObj['data'] = querys
    }
    axios({
      url: `${window.location.protocol}//${window.location.host}/api${path}`,
      method: method,
      header: headers,
      ...reqObj
    })
        .then((res) => {
          console.log("request返回res数据", res)
          /* 判断正确数据的状态码 */
          switch (String(res.status)) {
            case "200":
            case "201":
            case "204":
              Message.success("成功")
              resolve(res)
              break
            case "404":
              Message.error("接口错误")
              break
            default:
              Message.error("失败")
              reject(res)
          }
          // if-else方式
          /*if (res.status === 200 || res.status === 201 || res.status === 204) {
            Toast.success("成功")
            resolve(res)
          } else {
            if (res.status === 404) {
              Toast.fail("接口错误")
            } else {
              Toast.fail("失败")
            }
            reject(res)
          }*/
        })
        .catch((err) => {
          console.log("request返回err数据", err)
          Message.error("请求错误")
          // reject(err)
        })
  })
}

export default {
  Requests,
}
